package com.itheima.controller;

import com.itheima.domain.CarItem;
import com.itheima.domain.Order;
import com.itheima.domain.Product;
import com.itheima.domain.User;
import com.itheima.service.CarItemService;
import com.itheima.service.OrderService;
import com.itheima.service.ProductService;
import com.itheima.service.UserService;
import com.itheima.utils.ProductUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Controller
public class CarController {
    @Autowired
    private CarItemService carItemService;
    @Autowired
    private ProductService productService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductUtils productUtils;

    @GetMapping("/orderCar")
    public String showOrderCar(Model model,
                               @RequestParam(required = false) String searchKeyword,
                               @RequestParam(defaultValue = "1") int page,
                               @RequestParam(defaultValue = "time_desc") String sort,
                               HttpSession session) {

        // 1. 检查用户登录状态
        User user = (User) session.getAttribute("user");
        if (user == null) {
            session.setAttribute("error", "请先登录账号!");
            return "redirect:/login";
        }

        // 2. 获取用户购物车所有商品
        List<CarItem> originalCarItemList = carItemService.findCarItemsByUserId(user.getUserId());
        int originalItemCount = originalCarItemList.size();

        // 3. 过滤并标记下架商品
        List<CarItem> allCarItemList = new ArrayList<>();
        int filteredItemCount = 0;

        for (CarItem carItem : originalCarItemList) {
            Product product = productService.findProductById(carItem.getProductId());
            if (product != null && product.getStatus() == 1) {
                allCarItemList.add(carItem);
            } else {
                // 将下架商品的carItem状态设为-1
                if (carItem.getStatus() != -1) {
                    carItem.setStatus(-1);
                    carItemService.updateCarItemStatus(carItem.getId(), -1);
                    filteredItemCount++;
                }
            }
        }

        if (filteredItemCount > 0) {
            model.addAttribute("carItemSuccess", "系统已自动过滤 " + filteredItemCount + " 件已下架或售罄商品!");
        }

        // 4. 关键词搜索过滤
        if (searchKeyword != null && !searchKeyword.trim().isEmpty()) {
            allCarItemList = allCarItemList.stream()
                    .filter(carItem -> {
                        Product product = productService.findProductById(carItem.getProductId());
                        return product != null &&
                                (product.getTitle().toLowerCase().contains(searchKeyword.toLowerCase()) ||
                                        product.getDescription().toLowerCase().contains(searchKeyword.toLowerCase()));
                    })
                    .collect(Collectors.toList());
        }

        // 5. 排序处理
        switch (sort) {
            case "time_asc":
                Collections.sort(allCarItemList, Comparator.comparing(CarItem::getCreateTime));
                break;
            case "time_desc":
            default:
                Collections.sort(allCarItemList, Comparator.comparing(CarItem::getCreateTime).reversed());
                break;
        }

        // 6. 分页处理
        int pageSize = 2;
        int totalPages = (int) Math.ceil((double) allCarItemList.size() / pageSize);
        page = Math.max(1, Math.min(page, totalPages));

        int startIndex = (page - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, allCarItemList.size());
        List<CarItem> currentPageOrders = allCarItemList.subList(startIndex, endIndex);

        // 7. 添加模型属性
        model.addAttribute("sort", sort);
        model.addAttribute("carItemList", currentPageOrders);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("orderItemQuantity", allCarItemList.size()); // 显示有效商品数量
        model.addAttribute("productUtils", productUtils);
        model.addAttribute("action", "cart");
        model.addAttribute("searchKeyword", searchKeyword);

        return "showOrder";
    }

    @RequestMapping("/addCarItem")
    public String addCarItem(@RequestParam(required = false) int productId,
                             HttpSession session,
                             RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            session.setAttribute("error", "请先登录账号!");
            return "redirect:/login";
        }
        Product product = productService.findProductById(productId);
        if (product == null || user.getUserId() == product.getUserId()) {
            redirectAttributes.addFlashAttribute("errorInfo", "不可购买自己的商品!");
            return "redirect:/showAllProducts";
        }
        int result = carItemService.insertCarItem(user.getUserId(), productId);
        if (result == -1) {
            redirectAttributes.addFlashAttribute("addCarItemError", "购物车已有此商品，无需重复添加！");
        } else if (result == 0) {
            redirectAttributes.addFlashAttribute("addCarItemError", "添加失败，请重试！");
        } else {
            redirectAttributes.addFlashAttribute("addCarItemSuccess", "已添加至购物车！");
        }

        return "redirect:/showAllProducts";
    }

    @RequestMapping("/carItemDelete")
    public String deleteCarItem(HttpSession session, RedirectAttributes redirectAttributes,
                                @RequestParam(required = false) int productId) {
        User user = (User) session.getAttribute("user");
        CarItem carItem = carItemService.findCarItemByUserIdAndProductId(user.getUserId(), productId);
        if (carItem != null) {
            int result = carItemService.deleteCarItem(carItem.getId());
            if (result > 0) {
                redirectAttributes.addFlashAttribute("carItemSuccess", "已将商品移出您的购物车！！");
            } else {
                redirectAttributes.addFlashAttribute("carItemError", "删除失败，请重试！");
            }
        } else {
            redirectAttributes.addFlashAttribute("carItemError", "删除失败，请重试！");
        }
        return "redirect:/orderCar";
    }

    @PostMapping("/carItemPay")
    public String carItemPay(@RequestParam(required = false) Integer carItemBuyerId,
                             @RequestParam(required = false) Integer carItemSellerId,
                             @RequestParam(required = false) Integer carItemProductId,
                             @RequestParam(required = false) Integer carItemId,
                             HttpSession session,
                             Model model) {
        System.out.println(carItemBuyerId);
        System.out.println(carItemSellerId);
        System.out.println(carItemProductId);
        //找出三个重要成分
        User carBuyer = userService.findUserById(carItemBuyerId);
        User carSeller = userService.findUserById(carItemSellerId);
        Product carProduct = productService.findProductById(carItemProductId);
        if (carProduct.getStatus() != 1) {
            model.addAttribute("carItemError", "商品已售出或已下架，无法购买，建议将商品出购物车！");
            return "orderCar";
        }
        //初始化订单
        Order order = new Order();
        // 1. 设置订单信息
        order.setProductId(carProduct.getProductId());
        order.setBuyerId(carBuyer.getUserId());
        order.setSellerId(carSeller.getUserId());
        order.setPrice(carProduct.getPrice());
        order.setStatus(0);
        order.setCreateTime(new Date());
        if (carBuyer.getAddress() == null || carBuyer.getAddress().equals("")) {
            model.addAttribute("cerItemError", "购买失败，请先回主页设置收货地址！");
            return "orderCar";
        }
        order.setAddress(carBuyer.getAddress());
        order.setBuyerPhone(carBuyer.getPhone());
        order.setSellerPhone(carSeller.getPhone());

        // 2. 生成订单号
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timeStr = sdf.format(new Date());
        Random random = new Random();
        int randomNum = random.nextInt(9000) + 1000;
        String orderNumber = "ORDER" + timeStr + randomNum + carBuyer.getUserId();
        order.setOrderNumber(orderNumber);

        int insertResult = orderService.insertOrder(order);

        if (insertResult > 0) {
            Order order1 = orderService.findOrderByOrderNumber(orderNumber);
            //传给前端提交的订单id
            productService.soldProductById(order1.getProductId());
            carItemService.deleteCarItem(carItemId);
            session.setAttribute("pendingPaymentOrderId", order1.getOrderId());
            session.setAttribute("pendingPaymentProductName", carProduct.getTitle());
            session.setAttribute("pendingPaymentPrice", order1.getPrice());
            return "redirect:/showAllOrder";
        } else {
            model.addAttribute("carItemError", "购买失败，请重试！");
            return "orderCar";
        }
    }

    //清除购物车提交的订单id
    @PostMapping("/clearPendingPayment")
    @ResponseBody
    public void clearPendingPayment(HttpSession session) {
        session.removeAttribute("pendingPaymentOrderId");
        session.removeAttribute("pendingPaymentProductName");
        session.removeAttribute("pendingPaymentPrice");
    }
}
